﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.Abstract;
using DomainModel.Entities;
using System.Data.Linq;

namespace DomainModel.Concrete
{
    public class SqlAnsweredQuestionsRepository : IAnsweredQuestionsRepository
    {
        private Table<AnsweredQuestion> answeredQuestionsTable;

        public SqlAnsweredQuestionsRepository(string connectionString)
        {
            answeredQuestionsTable = (new DataContext(connectionString)).GetTable<AnsweredQuestion>();
        }

        public IQueryable<AnsweredQuestion> AnsweredQuestions
        {
            get { return answeredQuestionsTable; }
        }

        public void SaveAnsweredQuestion(AnsweredQuestion answeredQuestion)
        {
            if (answeredQuestion.AnsweredQuestionID == 0)
            {
                //It's a new answered question
                answeredQuestionsTable.InsertOnSubmit(answeredQuestion);
            }
            else
            {
                //It's an existing answered question
                answeredQuestionsTable.Attach(answeredQuestion);

                //Tell DataContext to detect any changes since last save
                answeredQuestionsTable.Context.Refresh(RefreshMode.KeepCurrentValues, answeredQuestion);
            }

            //Submit the changes
            answeredQuestionsTable.Context.SubmitChanges();
        }

        public void DeleteAnsweredQuestion(AnsweredQuestion answeredQuestion)
        {
            answeredQuestionsTable.DeleteOnSubmit(answeredQuestion);
            answeredQuestionsTable.Context.SubmitChanges();
        }
    }
}
